<?php
    require_once '../funcoes.php';
    $conexao = new Conexao();
    
    $id_usuario = $_SESSION['usuario']['id'];
    $busca = $_SESSION['busca'];    
    unset ($_SESSION['busca']);
    
    insereBusca($busca, $id_usuario);
		
    $response = array();

    $query = "	SELECT
		      CASE (SELECT COUNT(*) FROM seguidores s WHERE s.id_seguido = o.id_usuario AND s.id_seguidor = $id_usuario)
			    WHEN 0 THEN 0
			    ELSE 1
		      END as sigoEle,
		      CASE (SELECT COUNT(*) FROM lido l WHERE l.id_marcador = o.id AND l.id_leitor = $id_usuario)
			    WHEN 0 THEN 0
			    ELSE 1
		      END as lido,
		      CASE (SELECT o.id_usuario = $id_usuario)
			    WHEN 0 THEN 0
			    ELSE 1
		      END as meuPost,
		      o.*,
		      u.nome
		FROM
		  ofertas o, usuario u
		WHERE
		  (titulo LIKE '%$busca%' OR conteudo LIKE '%$busca%' OR u.nome LIKE '%$busca%') AND
		  o.id_usuario = u.id";
    
    //echo $query;
    $result = mysql_query($query);


    while ($row = mysql_fetch_assoc($result)) {
	
	    $SQL = "SELECT path FROM foto WHERE id_oferta = " . $row['id'];
	    
	    $resultFoto = mysql_query($SQL);
	    
	    $arrFotos = array();
	    while($foto = mysql_fetch_array($resultFoto)){
		array_push($arrFotos, $foto['path']);
	    }
	
	    if($row['compartilhado']){
		$row['nome'] .= " via ".$row['compartilhado'];
		$row['id_usuario'] = 'c';
	    }
	    
	    $mostrarSeguir = 0;
	    
	    if(!$row['meuPost'] && !$row['sigoEle']){
		$mostrarSeguir = 1;
	    }
	    
	    $response[] = array(
		    'lat'	=> $row['latitude'],
		    'lng'	=> (string) $row['longitude'],
		    'content'	=>  $row['conteudo'],
		    'icon'	=>  $row['icone'],
		    'dtPost'	=> formata_data($row['dataPost']),
		    'titulo'	=> $row['titulo'],
		    'id'	=> $row['id'] ,
		    'id_usuario'=> $row['id_usuario'],
		    'nome'	=> $row['nome'],
		    'dataFim'	=> $row['dataFim'],
		    'lido'	=> $row['lido'],
		    'mostrarSeguir' => $mostrarSeguir,
		    'fotos'	    => $arrFotos
	    );
    }

    echo json_encode($response);
?>

